package cn.kailangtu.dataspot.services;

import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import androidx.core.app.NotificationCompat;
import java.util.List;
import cn.kailangtu.dataspot.activify.SplashActivity;

public class WatchdogService extends Service {
    public WatchdogService() {
    }

    private static final int NOTIFICATION_ID = 1001;
    private static final long CHECK_INTERVAL = 15000; // 1分钟检测一次
    private Handler mHandler = new Handler();

    // 目标服务检测
    private final Runnable mCheckRunnable = new Runnable() {
        @Override
        public void run() {
            if (!isActivityInStack()) {
                restartTargetService();
            }
            mHandler.postDelayed(this, CHECK_INTERVAL);
        }
    };

    @Override
    public void onCreate() {
        super.onCreate();

    }

    @SuppressLint("ForegroundServiceType")
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        mHandler.post(mCheckRunnable);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel("persident", "persident",
                    NotificationManager.IMPORTANCE_LOW);
            NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            manager.createNotificationChannel(channel);
            Notification notification = new NotificationCompat.Builder(this, "persident")
                    .setAutoCancel(true)
                    .setCategory(Notification.CATEGORY_SERVICE)
                    .setOngoing(true)
                    .setPriority(NotificationManager.IMPORTANCE_LOW).build();
            startForeground(23, notification);
        }

        return START_STICKY;
    }

    // 构建前台通知


    // 检测目标服务是否运行
    private boolean isTargetServiceRunning() {
        ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);

        for (ActivityManager.RunningServiceInfo service :
                manager.getRunningServices(Integer.MAX_VALUE)) {
            Log.d("SHOOTLEE_WATCHDOG",service.service.getClassName());
            if ("cn.kailangtu.dataspot".equals(service.service.getClassName())) {
                return true;
            }
        }
        return false;
    }

    private boolean isActivityInStack() {
        ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
        List<ActivityManager.AppTask> tasks = am.getAppTasks();
        for (ActivityManager.AppTask task : tasks) {
            ActivityManager.RecentTaskInfo info = task.getTaskInfo();
            Log.d("SHOOTLEE_WATCHDOG",info.baseActivity.getClassName());
            if (info.baseActivity.getClassName().contains("MainActivity")) {
                return true;
            }
            else if(info.baseActivity.getClassName().contains("MainLowActivity"))
            {
                return true;
            }
            else if(info.baseActivity.getClassName().contains("SplashActivity"))
            {
                return true;
            }
        }
        return false;
    }

    // 重启目标服务
    private void restartTargetService() {
        Log.d("SHOOTLEE_WATCHDOG","打开程序");
        Intent serviceIntent = new Intent(this, SplashActivity.class);
       this.startActivity(serviceIntent);
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onDestroy() {
        mHandler.removeCallbacks(mCheckRunnable);
        super.onDestroy();
        // 自重启逻辑
        startService(new Intent(this, WatchdogService.class));
    }
}